package com.xjgzinfo.usdp.web.rest;

import com.xjgzinfo.usdp.AvueServer4jApp;
import com.xjgzinfo.usdp.config.TestSecurityConfiguration;
import com.xjgzinfo.usdp.domain.BladeVisualComponent;
import com.xjgzinfo.usdp.repository.BladeVisualComponentRepository;
import com.xjgzinfo.usdp.service.BladeVisualComponentService;
import com.xjgzinfo.usdp.service.dto.BladeVisualComponentDTO;
import com.xjgzinfo.usdp.service.mapper.BladeVisualComponentMapper;
import com.xjgzinfo.usdp.service.dto.BladeVisualComponentCriteria;
import com.xjgzinfo.usdp.service.BladeVisualComponentQueryService;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import javax.persistence.EntityManager;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Integration tests for the {@link BladeVisualComponentResource} REST controller.
 */
@SpringBootTest(classes = { AvueServer4jApp.class, TestSecurityConfiguration.class })
@AutoConfigureMockMvc
@WithMockUser
public class BladeVisualComponentResourceIT {

    private static final String DEFAULT_NAME = "AAAAAAAAAA";
    private static final String UPDATED_NAME = "BBBBBBBBBB";

    private static final String DEFAULT_CONTENT = "AAAAAAAAAA";
    private static final String UPDATED_CONTENT = "BBBBBBBBBB";

    @Autowired
    private BladeVisualComponentRepository bladeVisualComponentRepository;

    @Autowired
    private BladeVisualComponentMapper bladeVisualComponentMapper;

    @Autowired
    private BladeVisualComponentService bladeVisualComponentService;

    @Autowired
    private BladeVisualComponentQueryService bladeVisualComponentQueryService;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restBladeVisualComponentMockMvc;

    private BladeVisualComponent bladeVisualComponent;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static BladeVisualComponent createEntity(EntityManager em) {
        BladeVisualComponent bladeVisualComponent = new BladeVisualComponent()
            .name(DEFAULT_NAME)
            .content(DEFAULT_CONTENT);
        return bladeVisualComponent;
    }
    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static BladeVisualComponent createUpdatedEntity(EntityManager em) {
        BladeVisualComponent bladeVisualComponent = new BladeVisualComponent()
            .name(UPDATED_NAME)
            .content(UPDATED_CONTENT);
        return bladeVisualComponent;
    }

    @BeforeEach
    public void initTest() {
        bladeVisualComponent = createEntity(em);
    }

    @Test
    @Transactional
    public void createBladeVisualComponent() throws Exception {
        int databaseSizeBeforeCreate = bladeVisualComponentRepository.findAll().size();
        // Create the BladeVisualComponent
        BladeVisualComponentDTO bladeVisualComponentDTO = bladeVisualComponentMapper.toDto(bladeVisualComponent);
        restBladeVisualComponentMockMvc.perform(post("/api/blade-visual-components").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(bladeVisualComponentDTO)))
            .andExpect(status().isCreated());

        // Validate the BladeVisualComponent in the database
        List<BladeVisualComponent> bladeVisualComponentList = bladeVisualComponentRepository.findAll();
        assertThat(bladeVisualComponentList).hasSize(databaseSizeBeforeCreate + 1);
        BladeVisualComponent testBladeVisualComponent = bladeVisualComponentList.get(bladeVisualComponentList.size() - 1);
        assertThat(testBladeVisualComponent.getName()).isEqualTo(DEFAULT_NAME);
        assertThat(testBladeVisualComponent.getContent()).isEqualTo(DEFAULT_CONTENT);
    }

    @Test
    @Transactional
    public void createBladeVisualComponentWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = bladeVisualComponentRepository.findAll().size();

        // Create the BladeVisualComponent with an existing ID
        bladeVisualComponent.setId(1L);
        BladeVisualComponentDTO bladeVisualComponentDTO = bladeVisualComponentMapper.toDto(bladeVisualComponent);

        // An entity with an existing ID cannot be created, so this API call must fail
        restBladeVisualComponentMockMvc.perform(post("/api/blade-visual-components").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(bladeVisualComponentDTO)))
            .andExpect(status().isBadRequest());

        // Validate the BladeVisualComponent in the database
        List<BladeVisualComponent> bladeVisualComponentList = bladeVisualComponentRepository.findAll();
        assertThat(bladeVisualComponentList).hasSize(databaseSizeBeforeCreate);
    }


    @Test
    @Transactional
    public void getAllBladeVisualComponents() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get all the bladeVisualComponentList
        restBladeVisualComponentMockMvc.perform(get("/api/blade-visual-components?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(bladeVisualComponent.getId().intValue())))
            .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
            .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString())));
    }
    
    @Test
    @Transactional
    public void getBladeVisualComponent() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get the bladeVisualComponent
        restBladeVisualComponentMockMvc.perform(get("/api/blade-visual-components/{id}", bladeVisualComponent.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(bladeVisualComponent.getId().intValue()))
            .andExpect(jsonPath("$.name").value(DEFAULT_NAME))
            .andExpect(jsonPath("$.content").value(DEFAULT_CONTENT.toString()));
    }


    @Test
    @Transactional
    public void getBladeVisualComponentsByIdFiltering() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        Long id = bladeVisualComponent.getId();

        defaultBladeVisualComponentShouldBeFound("id.equals=" + id);
        defaultBladeVisualComponentShouldNotBeFound("id.notEquals=" + id);

        defaultBladeVisualComponentShouldBeFound("id.greaterThanOrEqual=" + id);
        defaultBladeVisualComponentShouldNotBeFound("id.greaterThan=" + id);

        defaultBladeVisualComponentShouldBeFound("id.lessThanOrEqual=" + id);
        defaultBladeVisualComponentShouldNotBeFound("id.lessThan=" + id);
    }


    @Test
    @Transactional
    public void getAllBladeVisualComponentsByNameIsEqualToSomething() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get all the bladeVisualComponentList where name equals to DEFAULT_NAME
        defaultBladeVisualComponentShouldBeFound("name.equals=" + DEFAULT_NAME);

        // Get all the bladeVisualComponentList where name equals to UPDATED_NAME
        defaultBladeVisualComponentShouldNotBeFound("name.equals=" + UPDATED_NAME);
    }

    @Test
    @Transactional
    public void getAllBladeVisualComponentsByNameIsNotEqualToSomething() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get all the bladeVisualComponentList where name not equals to DEFAULT_NAME
        defaultBladeVisualComponentShouldNotBeFound("name.notEquals=" + DEFAULT_NAME);

        // Get all the bladeVisualComponentList where name not equals to UPDATED_NAME
        defaultBladeVisualComponentShouldBeFound("name.notEquals=" + UPDATED_NAME);
    }

    @Test
    @Transactional
    public void getAllBladeVisualComponentsByNameIsInShouldWork() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get all the bladeVisualComponentList where name in DEFAULT_NAME or UPDATED_NAME
        defaultBladeVisualComponentShouldBeFound("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME);

        // Get all the bladeVisualComponentList where name equals to UPDATED_NAME
        defaultBladeVisualComponentShouldNotBeFound("name.in=" + UPDATED_NAME);
    }

    @Test
    @Transactional
    public void getAllBladeVisualComponentsByNameIsNullOrNotNull() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get all the bladeVisualComponentList where name is not null
        defaultBladeVisualComponentShouldBeFound("name.specified=true");

        // Get all the bladeVisualComponentList where name is null
        defaultBladeVisualComponentShouldNotBeFound("name.specified=false");
    }
                @Test
    @Transactional
    public void getAllBladeVisualComponentsByNameContainsSomething() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get all the bladeVisualComponentList where name contains DEFAULT_NAME
        defaultBladeVisualComponentShouldBeFound("name.contains=" + DEFAULT_NAME);

        // Get all the bladeVisualComponentList where name contains UPDATED_NAME
        defaultBladeVisualComponentShouldNotBeFound("name.contains=" + UPDATED_NAME);
    }

    @Test
    @Transactional
    public void getAllBladeVisualComponentsByNameNotContainsSomething() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        // Get all the bladeVisualComponentList where name does not contain DEFAULT_NAME
        defaultBladeVisualComponentShouldNotBeFound("name.doesNotContain=" + DEFAULT_NAME);

        // Get all the bladeVisualComponentList where name does not contain UPDATED_NAME
        defaultBladeVisualComponentShouldBeFound("name.doesNotContain=" + UPDATED_NAME);
    }

    /**
     * Executes the search, and checks that the default entity is returned.
     */
    private void defaultBladeVisualComponentShouldBeFound(String filter) throws Exception {
        restBladeVisualComponentMockMvc.perform(get("/api/blade-visual-components?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(bladeVisualComponent.getId().intValue())))
            .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME)))
            .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString())));

        // Check, that the count call also returns 1
        restBladeVisualComponentMockMvc.perform(get("/api/blade-visual-components/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("1"));
    }

    /**
     * Executes the search, and checks that the default entity is not returned.
     */
    private void defaultBladeVisualComponentShouldNotBeFound(String filter) throws Exception {
        restBladeVisualComponentMockMvc.perform(get("/api/blade-visual-components?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("$").isEmpty());

        // Check, that the count call also returns 0
        restBladeVisualComponentMockMvc.perform(get("/api/blade-visual-components/count?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(content().string("0"));
    }

    @Test
    @Transactional
    public void getNonExistingBladeVisualComponent() throws Exception {
        // Get the bladeVisualComponent
        restBladeVisualComponentMockMvc.perform(get("/api/blade-visual-components/{id}", Long.MAX_VALUE))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateBladeVisualComponent() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        int databaseSizeBeforeUpdate = bladeVisualComponentRepository.findAll().size();

        // Update the bladeVisualComponent
        BladeVisualComponent updatedBladeVisualComponent = bladeVisualComponentRepository.findById(bladeVisualComponent.getId()).get();
        // Disconnect from session so that the updates on updatedBladeVisualComponent are not directly saved in db
        em.detach(updatedBladeVisualComponent);
        updatedBladeVisualComponent
            .name(UPDATED_NAME)
            .content(UPDATED_CONTENT);
        BladeVisualComponentDTO bladeVisualComponentDTO = bladeVisualComponentMapper.toDto(updatedBladeVisualComponent);

        restBladeVisualComponentMockMvc.perform(put("/api/blade-visual-components").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(bladeVisualComponentDTO)))
            .andExpect(status().isOk());

        // Validate the BladeVisualComponent in the database
        List<BladeVisualComponent> bladeVisualComponentList = bladeVisualComponentRepository.findAll();
        assertThat(bladeVisualComponentList).hasSize(databaseSizeBeforeUpdate);
        BladeVisualComponent testBladeVisualComponent = bladeVisualComponentList.get(bladeVisualComponentList.size() - 1);
        assertThat(testBladeVisualComponent.getName()).isEqualTo(UPDATED_NAME);
        assertThat(testBladeVisualComponent.getContent()).isEqualTo(UPDATED_CONTENT);
    }

    @Test
    @Transactional
    public void updateNonExistingBladeVisualComponent() throws Exception {
        int databaseSizeBeforeUpdate = bladeVisualComponentRepository.findAll().size();

        // Create the BladeVisualComponent
        BladeVisualComponentDTO bladeVisualComponentDTO = bladeVisualComponentMapper.toDto(bladeVisualComponent);

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restBladeVisualComponentMockMvc.perform(put("/api/blade-visual-components").with(csrf())
            .contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(bladeVisualComponentDTO)))
            .andExpect(status().isBadRequest());

        // Validate the BladeVisualComponent in the database
        List<BladeVisualComponent> bladeVisualComponentList = bladeVisualComponentRepository.findAll();
        assertThat(bladeVisualComponentList).hasSize(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    public void deleteBladeVisualComponent() throws Exception {
        // Initialize the database
        bladeVisualComponentRepository.saveAndFlush(bladeVisualComponent);

        int databaseSizeBeforeDelete = bladeVisualComponentRepository.findAll().size();

        // Delete the bladeVisualComponent
        restBladeVisualComponentMockMvc.perform(delete("/api/blade-visual-components/{id}", bladeVisualComponent.getId()).with(csrf())
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        List<BladeVisualComponent> bladeVisualComponentList = bladeVisualComponentRepository.findAll();
        assertThat(bladeVisualComponentList).hasSize(databaseSizeBeforeDelete - 1);
    }
}
